const path = require('path');
const fs = require('fs');
const jwt = require('jsonwebtoken'); // 引入jwt

const secretKey = 'your-secret-key';  // 在实际项目中，应该将密钥保存在安全的地方

const dirController = {
  // 创建子目录
  createDirectory: async (ctx) => {
    const { dirName } = ctx.request.body;
    const dirPath = path.join(ctx.state.currentDir, dirName);

    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath);
      ctx.body = { status: 0, msg: '目录创建成功' };
    } else {
      ctx.status = 400;
      ctx.body = { status: 1, msg: '目录已存在' };
    }
  },



  



  // 重命名子目录
  renameDirectory: async (ctx) => {
    const { oldName, newName } = ctx.request.body;
    const oldPath = path.join(ctx.state.currentDir, oldName);
    const newPath = path.join(ctx.state.currentDir, newName);

    if (fs.existsSync(oldPath)) {
      fs.renameSync(oldPath, newPath);
      ctx.body = { status: 0, msg: '目录重命名成功' };
    } else {
      ctx.status = 404;
      ctx.body = { status: 1, msg: '目录不存在' };
    }
  },

  // 获取当前目录下的文件和目录列表
  listDirectory: async (ctx) => {
    console.log(ctx.state.user.currentDir,'user')
    const dirPath = ctx.state.currentDir;
    const contents = fs.readdirSync(dirPath).map(file => {
      const filePath = path.join(dirPath, file);
      return fs.statSync(filePath).isDirectory() ? `${file}/` : file;
    });
    ctx.body = { status: 0, contents };
  },

  // 切换目录
  changeDirectory: async (ctx) => {
    const { newDir } = ctx.request.body;
    const targetDir = path.resolve(ctx.state.currentDir, newDir);

    if (fs.existsSync(targetDir) && fs.statSync(targetDir).isDirectory()) {
      ctx.state.currentDir = targetDir;  // 更新当前目录

      // 生成新的 token 并返回给客户端
      const updatedToken = jwt.sign(
        { username: ctx.state.user.username, currentDir: ctx.state.currentDir },
        secretKey,
        { expiresIn: '1h' }  // 可根据需要调整 token 的有效期
      );
      console.log(updatedToken,'更新后的token')
      const decoded = jwt.verify(updatedToken, secretKey);
      console.log('看看decoded',decoded)

      ctx.body = { status: 0, msg: '目录切换成功', token: updatedToken };
    } else {
      ctx.status = 400;
      ctx.body = { status: 1, msg: '无效的目录路径' };
    }
  },

  // 获取当前目录
  getCurrentDirectory: async (ctx) => {
    console.log(ctx.state)
    ctx.body = { status: 0, currentPath: ctx.state.currentDir };
  },
};

module.exports = dirController;


